How to refactor and optimize function

welcome to shbcf.ru